package com.shujia.mr.DianXin2;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

////reduce输入<"1001",["$20180603-50","#万寿福宫，北京"]>
////reduce输出<"20180603-万寿福宫，北京","50">
//public class DianXinReducer2 extends Reducer<Text, Text, Text, Text> {
//    @Override
//    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
//        String city = "未知";
//        String time = "无";
//        String PhoneNumber = "无";
//        for (Text value : values) {
//            String line = value.toString();
//            if (line.startsWith("*")) {
//                String[] infos = line.substring(1).split("-");
//                if (infos[0]==null || "".equals(infos[0])) {
//                    PhoneNumber = "无";
//                }else {
//                    PhoneNumber = infos[0];
//                }
//                time = infos[1];
//                if (time == null || "".equals(time)) {
//                    time = "无";
//                }else {
//                    time = infos[1];
//                }
//
//            } else if (line.startsWith("#")) {
//
//                city = line.substring(1);
//                if (city == null || "".equals(city)) {
//                    city = "未知";
//                }else {
//                    city = line.substring(1);
//                }
//
//            }
//        }
//        context.write(new Text(PhoneNumber+"-"+city),new Text(time));
//    }
//}
public class DianXinReducer2 extends Reducer<Text, Text, Text, Text> {
    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        String city = "未知";
        String time = "无"; // 初始化time为"无"
        String PhoneNumber = "无"; // 初始化PhoneNumber为"无"
        for (Text value : values) {
            String line = value.toString();
            if (line.startsWith("*")) {
                String[] infos = line.substring(1).split("-");
                if (infos.length > 0) {
                    PhoneNumber = infos.length > 0 ? infos[0] : "无";
                }
                if (infos.length > 1) {
                    time = infos[1];
                }
                // 省略了对time的再次非空检查，因为已经初始化为"无"
            } else if (line.startsWith("#")) {
                city = line.length() > 1 ? line.substring(1) : "未知";
                // 省略了对city的非空检查，因为已经初始化为"未知"
            }
        }
        context.write(new Text(PhoneNumber + "-" + city), new Text(time));
    }
}